package com.entertainment.ticketing.repository;

import com.entertainment.ticketing.entity.TicketInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import jakarta.persistence.LockModeType;

import java.util.List;
import java.math.BigDecimal;

public interface TicketInfoRepository extends JpaRepository<TicketInfo, Long> {
    List<TicketInfo> findByEvent_Id(Long eventId);
    List<TicketInfo> findByEvent_IdAndStatus(Long eventId, Byte status);
    List<TicketInfo> findByIdIn(List<Long> ids);

    Page<TicketInfo> findByEvent_Id(Long eventId, Pageable pageable);

    @Query("select t from TicketInfo t where (:keyword is null or lower(t.ticketType) like lower(concat('%', :keyword, '%')))"
    )
    Page<TicketInfo> searchByTicketType(String keyword, Pageable pageable);

    @Query("select t from TicketInfo t where (:eventId is null or t.event.id = :eventId) and (:status is null or t.status = :status) and (:keyword is null or lower(t.ticketType) like lower(concat('%', :keyword, '%'))) ")
    Page<TicketInfo> searchAdmin(Long eventId, Byte status, String keyword, Pageable pageable);

    @Query("select min(t.price) from TicketInfo t where t.event.id = :eventId and t.status = 1")
    BigDecimal getLowestPriceByEventId(Long eventId);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select t from TicketInfo t where t.id in :ids")
    List<TicketInfo> findByIdInForUpdate(List<Long> ids);
}